<template>
  <div class="app-container">
    <!-- 过滤 -->
    <div class="filter-container">
      <el-input v-model="listQuery.categoryEncoding" placeholder="分类编码" style="width: 200px;" class="filter-item" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="resetHandler">
        重置
      </el-button>
    </div>
    <div style="margin-bottom: 10px;">
      <el-button class="filter-item" type="primary" @click="openDialog">
        添加
      </el-button>
      <!-- 选中的数据不为空，才解除禁用状态 -->
      <el-tooltip class="item" effect="dark" content="批量修改" placement="bottom">
        <el-button class="filter-item" :disabled="!ids.length" type="primary" @click="openConfirm(editBatchList, 'editBatch')">
          修改
        </el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="批量删除" placement="bottom">
        <el-button class="filter-item" :disabled="!ids.length" type="danger" @click="openConfirm(ids)">
          删除
        </el-button>
      </el-tooltip>
    </div>

    <!-- 表格 -->
    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" />
      <el-table-column align="center" label="编号">
        <template slot-scope="{row}">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="分类编码">
        <template slot-scope="{row}">
          <!-- 判断ids(选中的数据)，是否有 row.id 的存在 true：显示输入框 false：显示span-->
          <template v-if="ids.includes(row.id)">
            <el-input v-model="row.categoryEncoding" size="small" />
          </template>
          <span v-else>{{ row.categoryEncoding }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="分类名称">
        <template slot-scope="{row}">
          <template v-if="ids.includes(row.id)">
            <el-input v-model="row.categoryName" size="small" />
          </template>
          <span v-else>{{ row.categoryName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="说明">
        <template slot-scope="{row}">
          <template v-if="ids.includes(row.id)">
            <el-input v-model="row.description" size="small" />
          </template>
          <span v-else>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="{row}">
          <!-- 悬浮提示效果 -->
          <el-tooltip class="item" effect="dark" content="添加" placement="bottom">
            <el-button type="primary" icon="el-icon-position" circle @click="openDialog(row, 'add')" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="修改" placement="bottom">
            <el-button type="primary" icon="el-icon-edit" circle @click="openDialog(row, 'edit')" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
            <el-button type="danger" icon="el-icon-delete" circle @click="openConfirm(row)" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />

    <!-- 对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item v-if="form.id" label="编号" :label-width="formLabelWidth">
          <el-input v-model="form.id" placeholder="编号" :disabled="true" autocomplete="off" />
        </el-form-item>
        <el-form-item label="父级分类" :label-width="formLabelWidth" prop="parentCategoryId">
          <el-select v-model="form.parentCategoryId" placeholder="父级分类">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.categoryName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类编码" :label-width="formLabelWidth" prop="categoryEncoding">
          <el-input v-model="form.categoryEncoding" placeholder="请输入分类编码" autocomplete="off" />
        </el-form-item>
        <el-form-item label="分类名称" :label-width="formLabelWidth" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" autocomplete="off" />
        </el-form-item>
        <el-form-item label="说明" :label-width="formLabelWidth" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="2" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { fetchList, fetchOne, save, edit, remove, editBatch, fetchParentExist } from '@/api/material-category'
export default {
  name: 'MaterialCategory',
  components: { Pagination },
  data() {
    return {
      // 功能标题
      title: '物料分类',
      tableKey: 0,
      listLoading: true,
      // 查询参数
      listQuery: {
        page: 1,
        size: 10,
        categoryEncoding: ''
      },
      // 表格数据
      list: null,
      // 总数
      total: 0,
      // 对话框显示
      dialogFormVisible: false,
      // 对话框宽度
      formLabelWidth: '120px',
      // 表单
      form: {
        id: '',
        categoryEncoding: '',
        categoryName: '',
        description: '',
        parentCategoryId: ''
      },
      // 对话框标题
      dialogTitle: '',
      // 校验规则
      rules: {
        categoryEncoding: [
          { required: true, message: '请输入分类编码', trigger: 'blur' }
        ],
        categoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 所有分类数据
      categoryList: null,
      // id数组，存放选中的数据
      ids: [],
      // 批量修改数据
      editBatchList: []
    }
  },
  created() {
    this.getList()
    this.getCategoryAllList()
  },
  methods: {
    /**
     * 查询
     */
    handleFilter() {
      this.getList()
    },
    /**
     * 重置
     */
    resetHandler() {
      this.listQuery = {
        page: 1,
        size: 10,
        categoryEncoding: ''
      }
    },
    /**
     * 获取列表
     */
    getList() {
      fetchList(this.listQuery).then(resp => {
        const { data } = resp
        this.total = data.total
        this.list = data.list
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 执行操作 修改和新增
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id) { // 有 id 就是执行修改，否则执行添加
            this.editHandler()
          } else {
            console.log('数据行内新增')
            this.addHandler()
          }
        } else {
          return false
        }
      })
    },
    /**
     * 开启对话框
     * @param {*} row 行数据
     * @param {String} handle 操作
     */
    openDialog(row, handle) {
      this.dialogFormVisible = true
      // 开启对话框清空表单数据
      this.form = {
        id: '',
        categoryEncoding: '',
        categoryName: '',
        description: '',
        parentCategoryId: ''
      }
      // 清除 rules 原因: 不清除会导致，使用同一个对话框，上一次的规则校验提示还存在
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      // 修改
      if (row.id && handle === 'edit') {
        this.dialogTitle = `修改${this.title}`
        console.log('数据行内，修改')
        this.getOne(row.id)
        return
      }
      // 数据行内，添加
      if (row.id && handle === 'add') {
        this.dialogTitle = `添加${this.title}`
        console.log('数据行内，添加')
        this.form.parentCategoryId = row.id
        return
      }
      // 新增
      this.dialogTitle = `添加${this.title}`
      console.log('列表上方和数据行内，添加')
    },
    /**
     * 获取单个信息
     * @param { Number } id 分类id
     */
    getOne(id) {
      fetchOne(id).then(resp => {
        this.form = resp.data
        // TODO 父级分类id不存在，使用当前分类id显示
        if (!this.form.parentCategoryId) {
          this.form.parentCategoryId = this.form.id
        }
      })
    },
    /**
     * 添加
     */
    addHandler() {
      save(this.form).then(resp => {
        this.$notify({
          title: '成功',
          message: resp.msg,
          type: 'success',
          duration: 5000
        })
      }).finally(() => {
        this.dialogFormVisible = false
        this.getList()
        this.getCategoryAllList() // 刷新 全部分类数据
      })
    },
    /**
     * 修改
     */
    editHandler() {
      edit(this.form).then(resp => {
        this.$notify({
          title: '成功',
          message: resp.msg,
          type: 'success',
          duration: 5000
        })
      }).finally(() => {
        this.dialogFormVisible = false
        this.getList()
        this.getCategoryAllList() // 刷新 全部分类数据
      })
    },
    /**
     * 批量修改
     * @param {*} editBatchList 待修改的数据
     */
    editBatchHandler(editBatchList) {
      console.log('处理的数据', editBatchList)
      editBatch(editBatchList).then(resp => {
        this.$notify({
          title: '成功',
          message: resp.msg,
          type: 'success',
          duration: 5000
        })
      }).finally(() => {
        this.getList()
        this.getCategoryAllList()
      })
    },
    /**
     * 获取对应id是否作为其他分类的父级而存在
     */
    getParentExist(ids) {
      fetchParentExist(ids).then(resp => {
        if (resp.msg !== '没有关联') {
          this.$message({
            message: resp.msg,
            type: 'warning',
            showClose: true,
            duration: 5000
          })
        }
      })
    },
    /**
     * 打开确认框
     * @param {*} row 行数据
     * @param {String} handle 操作
     */
    openConfirm(row, handle) {
      const ids = []
      // 提示部分内容
      let content = '永久删除'
      if (row.id) { // 行内删除
        console.log('行内删除')
        ids.push(row.id)
        this.getParentExist(ids)
      } else if (handle === 'editBatch') { // 批量修改
        console.log('执行批量修改')
        ids.push(...this.ids)
        content = '批量修改'
      } else { // 表格上方删除
        console.log('表格上方删除')
        // 数组拼接
        ids.push(...row)
        this.getParentExist(ids)
      }
      console.log('ids', ids)
      this.$confirm(`此操作将${content}编号为 <span style="word-wrap:break-word;font-weight: bold;"> ${ids} </span> 的数据`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        if (handle === 'editBatch') { // 批量处理操作
          this.editBatchHandler(this.editBatchList)
        } else { // 删除操作
          this.deleteHandler(ids)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    /**
     * 删除
     * @param { Number } ids 行数据id
     */
    deleteHandler(ids) {
      console.log(ids)
      remove(ids).then(resp => {
        console.log(resp)
        this.$notify({
          title: '成功',
          message: resp.msg,
          type: 'success',
          duration: 5000
        })
      }).finally(() => {
        this.getList()
        this.getCategoryAllList() // 刷新 全部分类数据
      })
    },
    /**
     * 获取全部分类数据
     */
    getCategoryAllList() {
      // TODO 目前就先写死了，后面有空再去试试，触底加载
      fetchList({ page: 1, size: 100 }).then(resp => {
        const { data } = resp
        this.categoryList = data.list
      })
    },
    /**
     * 选中改变触发
     * @param { Array } val 选中的行数据
     */
    handleSelectionChange(val) {
      const temp = []
      // 遍历取出选中项中的id
      val.map((item) => {
        temp.push(item.id)
      })
      // 赋予 ids
      this.ids = temp
      this.editBatchList = val
    }
  }
}
</script>
<style scoped></style>
